package com.xspace.android.xafcommon.network;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import android.util.Log;

import com.xspace.android.xafcommon.network.apn.ApnNode;
import com.xspace.android.xafcommon.network.apn.ApnUtil;
import com.xspace.android.xafcommon.network.apn.ApnUtil.APNname;
import com.xspace.android.xafcommon.network.message.AResponseMsg;

public class HttpConnectWrapper {
	private int CONNECTION_TIMEOUT = 1000 * 30;
	private int CONNECTION_TIMEOUT_WAP = 1000 * 45;
	private int SO_TIMEOUT = 1000 * 20;
	private byte[] buff = new byte[1024 * 15];
	private static ApnNode apnNode = null;

	public byte[] httpGet(String url, Hashtable<?, ?> otherDate,
			String validHeaderTag, List<NameValuePair> requestPair,
			AResponseMsg response) throws IOException {
		HttpUtil.isLegalHttpUrl(url);
		HttpResponse httpConn = openConnectionGet(url, otherDate, requestPair);
		return getHttpContent(httpConn, response);
	}

	public byte[] httpPost(String url, String contentType, byte[] postdata,
			Hashtable<?, ?> otherDate, List<NameValuePair> requestPair,
			AResponseMsg response) throws IOException {
		HttpUtil.isLegalHttpUrl(url);
		HttpResponse httpConn = openConnectionPost(url, contentType, otherDate,
				postdata, requestPair);
		return getHttpContent(httpConn, response);
	}

	private HttpResponse openConnectionGet(String url,
			Hashtable<?, ?> otherDate, List<NameValuePair> requestPair)
			throws IOException {
		HttpResponse httpConn = null;
		HttpUtil.isLegalHttpUrl(url);
		HttpClient httpClient = new DefaultHttpClient();
		if (NetConstant.cookieStore != null) {
			((AbstractHttpClient) httpClient)
					.setCookieStore(NetConstant.cookieStore);
		}
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				SO_TIMEOUT);
		HttpGet httpGet = null;
		setProxy(httpClient);
		String paramStr = "";
		Iterator<?> iter = otherDate.entrySet().iterator();
		while (iter.hasNext()) {
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			paramStr += paramStr = "&" + key + "=" + val;
		}

		if (!paramStr.equals("")) {
			paramStr = paramStr.replaceFirst("&", "?");
			url += paramStr;
		}
		httpGet = new HttpGet(url);
		if (otherDate != null) {
			Enumeration<?> perpertyKeys = otherDate.keys();
			while (perpertyKeys.hasMoreElements()) {
				String key = (String) perpertyKeys.nextElement();
				String value = (String) otherDate.get(key);
				httpGet.addHeader(key, value);
			}
		}
		if (httpClient != null && httpClient.getConnectionManager() != null) {
			httpConn = httpClient.execute(httpGet);
		}
		NetConstant.cookieStore = ((AbstractHttpClient) httpClient)
				.getCookieStore();
		return httpConn;
	}

	private HttpResponse openConnectionPost(String url, String contentType,
			Hashtable<?, ?> otherDate, byte[] postdata,
			List<NameValuePair> requestPair) throws IOException {
		HttpClient httpClient = new DefaultHttpClient();
		if (NetConstant.cookieStore != null) {
			((AbstractHttpClient) httpClient)
					.setCookieStore(NetConstant.cookieStore);
		}
		HttpResponse httpConn = null;
		HttpPost httpPost = null;
		setProxy(httpClient);
		httpPost = new HttpPost(url);
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				SO_TIMEOUT);
		if (null != requestPair && requestPair.size() > 0) {
			httpPost.setEntity(new UrlEncodedFormEntity(requestPair, HTTP.UTF_8));
		}
		if (otherDate != null && !otherDate.isEmpty()) {
			MultipartEntity entity = new MultipartEntity(null, null,
					Charset.forName(HTTP.UTF_8));
			Enumeration<?> perpertyKeys = otherDate.keys();
			while (perpertyKeys.hasMoreElements()) {
				String key = (String) perpertyKeys.nextElement();
				byte[] value = (byte[]) otherDate.get(key);
				entity.addPart(key, new InputStreamBody(
						new ByteArrayInputStream(value), key + ".jpg"));
			}
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 60);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, 1000 * 60);
			httpPost.setEntity(entity);
		}
		if (null != postdata) {
			httpPost.addHeader("mobileEncrypts", "true");
			httpPost.setEntity(new StringEntity(new String(postdata,
					"ISO-8859-1")));
		}
		httpPost.addHeader("Content-type", contentType);
		httpConn = httpClient.execute(httpPost);
		NetConstant.cookieStore = ((AbstractHttpClient) httpClient)
				.getCookieStore();
		return httpConn;

	}

	private byte[] getHttpContent(HttpResponse httpConn, AResponseMsg response)
			throws IOException {
		int code = httpConn.getStatusLine().getStatusCode();
		if (code != HttpURLConnection.HTTP_OK
				&& code != HttpURLConnection.HTTP_MOVED_TEMP) {
			response.retCode = code;
			return null;

		}
		if (null != response) {
			response.retCode = code;
		}
		HttpEntity entity = httpConn.getEntity();
		if (null != entity) {
			return consume((int) entity.getContentLength(), entity.getContent());
		}
		return null;

	}

	private byte[] consume(int contentLength, InputStream dis)
			throws IOException {
		byte[] result = null;
		if (contentLength == -1) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while (true) {
				int len = dis.read(buff, 0, buff.length);
				if (len == -1)
					break;
				baos.write(buff, 0, len);
			}
			result = baos.toByteArray();
			if (baos != null)
				baos.close();
			dis.close();
			baos = null;
		} else {
			result = new byte[contentLength];
			int currLen = 0;
			while (currLen < contentLength) {
				int len = dis.read(result, currLen, contentLength - currLen);
				if (len == -1)
					break;
				currLen += len;
			}
			dis.close();
			if (currLen < contentLength) {
				return null;
			}
		}
		return result;

	}

	private synchronized void setProxy(HttpClient httpClient) {
		boolean isCMWap = ApnUtil.isWap();
		if (isCMWap) {
			int port = 80;
			//移动联通 默认10.0.0.172 电信10.0.0.200
			String proxyIp = "10.0.0.172";
			String wrapname=ApnUtil.getWapName();
			Log.v("xafcommon", "wrapname:"+wrapname);
			//电信多种机型测试发现接入点名称大都为#777或者null 使用排除法确定
			if(APNname.WAP_3G.equals(wrapname) || APNname.CMWAP.equals(wrapname) || APNname.UNIWAP.equals(wrapname)){
				
			}
			else{
			 proxyIp = "10.0.0.200";
			}
			//if (apnNode == null) {
				//apnNode = ApnUtil.getDefaultAPN();
			//}
			// if (apnNode != null) {
			// if (apnNode.getPort() != null && !apnNode.getPort().equals("")) {
			// port = Integer.parseInt(apnNode.getPort());
			// }
			// if (apnNode.getProxy() != null
			// && !apnNode.getProxy().equals("")) {
			// proxyIp = apnNode.getProxy();
			// }
			// }
			HttpHost proxy = new HttpHost(proxyIp, port);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_WAP);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					CONNECTION_TIMEOUT_WAP);
			httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					proxy);
		}
	}
}
